<?php
/**
 * Description of YCommon_Weixin_Validation
 *
 * @author balcksunshine
 */
defined('CALLYUMMY_PATH_INCLUDE') or define('CALLYUMMY_PATH_INCLUDE', dirname($_SERVER['DOCUMENT_ROOT']) . '/include');
require_once CALLYUMMY_PATH_INCLUDE . '/tool/YTool_Log.php';
require_once CALLYUMMY_PATH_INCLUDE . '/common/YCommon_City_CodeMap.php';
require_once CALLYUMMY_PATH_INCLUDE . '/common/YCommon_Stock_CodeMap.php';
require_once CALLYUMMY_PATH_INCLUDE . '/common/YCommon_Lottery_CodeMap.php';
require_once CALLYUMMY_PATH_INCLUDE . '/common/YCommon_Express_CodeMap.php';
class YCommon_Weixin_Response
{
    public function __construct() {
    }
    
    public function doResponse($keyword)
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      	//extract post data
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();

            //add some log to data mining
            YTool_Log::addFileLog('callyummy', array(
                           'fromUsername' => $fromUsername,
                               'fromUsername' => $fromUsername,
                               '$toUsername' => $toUsername,
                               'keyword' => $keyword,
                               'time' => $time,
                               ));
            
            if(!empty( $keyword ))
            {
                $citycode = YCommon_City_CodeMap::getCityCodeByName($keyword);
                $stockcode = YCommon_Stock_CodeMap::getStockCodeByName($keyword);
                $lotterycode = YCommon_Lottery_CodeMap::getLotteryCodeByName($keyword);
                list($expresscode, $expressno) = YCommon_Express_CodeMap::getExpressCodeByName($keyword);
                if ((strpos($keyword, 'DZ') !== false) || (strpos($keyword, 'dz') !== false) || (strpos($keyword, 'HH') !== false) || (strpos($keyword, 'hh') !== false))  //包含DZ / HH字串的视为查询惠惠助手优惠信息的请求
                {
                    $msgType = "news";
                    $content = '';
                    switch (substr($keyword, 2))    //返回去除了HH的字串
                    {
                        case '数码家电':{
                            $content = $this->do_post_request("http://zhushou.huihui.cn/api/hui/latest.json?channel=PROFESSIONAL~WEEKLY~PRICE~DEAL&category=1");
                        }break;
                        case '服饰鞋包':{
                            $content = $this->do_post_request("");
                        }break;
                        case '食品百货':{
                            $content = $this->do_post_request("http://zhushou.huihui.cn/api/hui/latest.json?channel=PROFESSIONAL~WEEKLY~PRICE~DEAL&category=16");
                        }break;
                        case '母婴玩具':{}break;
                        case '运动健康':{}break;
                        case '海外购':{}break;
                        case '美妆个护':{}break;
                        case '其他类别':{}break;
                        default:{
                            $content = $this->do_post_request("http://zhushou.huihui.cn/api/hui/latest.json");
                        }break;
                    }
                    $contentArray = json_decode($content, true);
                    $newArray = array();
                    $flag = 0;
                    foreach ($contentArray as $item)
                    {
                        if ($item['targetUrl'] && $item['title'] && $item['subTitle'] && $item['imageUrl'] && $flag < 9)
                        {
                            $flag++;
                            $newArray[] = $item;
                        }
                    }
                    $ss = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <ArticleCount>%s</ArticleCount>
                        <Articles>
                         <item>
                        <Title><![CDATA[%s]]></Title> 
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>
                        <item>
                        <Title><![CDATA[%s]]></Title> 
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>
                        <item>
                        <Title><![CDATA[%s]]></Title> 
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>
                        <item>
                        <Title><![CDATA[%s]]></Title> 
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>
                        <item>
                        <Title><![CDATA[%s]]></Title> 
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>
                        <item>
                        <Title><![CDATA[%s]]></Title> 
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>
                        <item>
                        <Title><![CDATA[%s]]></Title> 
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>
                        <item>
                        <Title><![CDATA[%s]]></Title> 
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>
                        <item>
                        <Title><![CDATA[%s]]></Title> 
                        <Description><![CDATA[%s]]></Description>
                        <PicUrl><![CDATA[%s]]></PicUrl>
                        <Url><![CDATA[%s]]></Url>
                        </item>
                        </Articles>
                        <FuncFlag>1</FuncFlag>
                        </xml> ";
                       $msgType = "news";
                       $sss = sprintf($ss, $fromUsername, $toUsername, $time, $msgType, $flag, $newArray[0]['title'], $newArray[0]['subTitle'], $newArray[0]['imageUrl'], $newArray[0]['targetUrl'], $newArray[1]['title'], $newArray[1]['subTitle'], $newArray[1]['imageUrl'], $newArray[1]['targetUrl'], $newArray[2]['title'], $newArray[2]['subTitle'], $newArray[2]['imageUrl'], $newArray[2]['targetUrl'], $newArray[3]['title'], $newArray[3]['subTitle'], $newArray[3]['imageUrl'], $newArray[3]['targetUrl'], $newArray[4]['title'], $newArray[4]['subTitle'], $newArray[4]['imageUrl'], $newArray[4]['targetUrl'], $newArray[5]['title'], $newArray[5]['subTitle'], $newArray[5]['imageUrl'], $newArray[5]['targetUrl'], $newArray[6]['title'], $newArray[6]['subTitle'], $newArray[6]['imageUrl'], $newArray[6]['targetUrl'], $newArray[7]['title'], $newArray[7]['subTitle'], $newArray[7]['imageUrl'], $newArray[7]['targetUrl'], $newArray[8]['title'], $newArray[8]['subTitle'], $newArray[8]['imageUrl'], $newArray[8]['targetUrl']);
                       echo ($sss);
                }
                elseif ((strpos($keyword, 'TQ') !== false) || (strpos($keyword, 'tq') !== false) || ($citycode))
                {
                    $citycode = isset($citycode) ? $citycode : '101272002';
                    $url = "http://m.weather.com.cn/data/" . $citycode . ".html";
                    $content = file_get_contents($url);
                    $contentArray = json_decode($content, true);
                    
                    $contentArray = $contentArray['weatherinfo'];
                    $weatherText = $contentArray['city'] . ': [' . $contentArray['date_y'] .  '][' . $contentArray['week'] . '],天气情况：'."\n".
                                    '今天[' . $contentArray['weather1'] . '，' . $contentArray['temp1'] . '，' . $contentArray['wind1'] . '，' . $contentArray['index_d'] . ']；'."\n".
                                    '明天[' . $contentArray['weather2'] . '，' . $contentArray['temp2'] . '，' . $contentArray['wind2'] . '，' . $contentArray['index48_d'] . ']；'."\n".
                                    '后天[' . $contentArray['weather3'] . '，' . $contentArray['temp3'] . '，' . $contentArray['wind3'] . '。';
                    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";
                    $msgType = "text";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $weatherText);
                    echo $resultStr;
                }
                elseif ($stockcode)
                {
                    $url = "http://api2.sinaapp.com/search/stock/?appkey=0020130430&appsecert=fa6095e113cd28fd&reqtype=text&keyword=" . $stockcode;
                    $content = file_get_contents($url);
                    $contentArray = json_decode($content, true);
                    
                    if (!$contentArray['errcode'])
                    {
                        $stockText = $contentArray['text']['content'];
                    }
                    else
                    {
                        $stockText = '查询股票信息失败了，sorry';
                    }
                    
                    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";
                    $msgType = "text";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $stockText);
                    echo $resultStr;
                }
                elseif ($lotterycode)
                {
                    $url = "http://api2.sinaapp.com/search/lottery/?appkey=0020130430&appsecert=fa6095e113cd28fd&reqtype=text&keyword=" . urlencode($lotterycode);
                    $content = file_get_contents($url);
                    $contentArray = json_decode($content, true);
                    
                    if (!$contentArray['errcode'])
                    {
                        $lotteryText = $contentArray['text']['content'];
                    }
                    else
                    {
                        $lotteryText = '查询彩票信息失败了，sorry';
                    }
                    
                    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";
                    $msgType = "text";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $lotteryText);
                    echo $resultStr;
                }
                elseif ($expresscode)
                {
                    $expresscode = trim($expresscode);
                    $expressno = trim($expressno);
                    $url = "http://wap.kuaidi100.com/wap_result.jsp?rand=" . rand(100000, 156546465) . "&id=$expresscode&fromWeb=null&postid=$expressno&sub=%E6%9F%A5%E8%AF%A";
                    $content = file_get_contents($url);
                    $realStr = '';
                    if (false === strstr($content, 'errordiv'))
                    {
                        $cut1 = explode('<p><strong>查询结果如下所示：</strong></p>', $content);
                        $cut2 = explode('<div style="margin:8px 0;padding:5px;background-color:#FFFAE2">', $cut1[1]);
                        $realStr = htmlspecialchars_decode($cut2[0]);

                        $realStr = str_replace('<p>&middot;', '', $realStr);
                        $realStr = str_replace('<br />', '', $realStr);
                        $realStr = str_replace('</p>', "\n", $realStr);
                    }
                    else
                    {
                        $realStr = '此单号暂无物流信息，请稍后再查。到快递公司官网查询下？';
                        $cut1 = explode('到快递公司<a href=\'', $content);
                        $cut2 = explode('\'>官网查询试试', $cut1[1]);
                        $officialUrl = $cut2[0];
                        $realStr .= $officialUrl;
                    }

                    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";
                    $msgType = "text";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $realStr);
                    echo $resultStr;
                    //add some log to data mining
                    YTool_Log::addFileLog('callyummy', array(
                        'url' => $url,
                        'result' => $realStr,
                        'content' => $content,
                        ));
                }
                else    //视为同irobot用英语沟通的请求
                {
                    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";
                    $msgType = "text";
                    $contentStr = "可以时时聊天啦，说英文哦!";
                    $contentStr = $this->do_post_request("http://pandorabots.com/pandora/talk?botid=97ec3cf40e345085&input=" . urlencode($keyword), $keyword);
                    $contentStr = explode('font color="green">', $contentStr);
                    $contentStr = explode('</font>', $contentStr[1]);
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr[0]);
                    echo $resultStr;
                }
            }
            else
            {
                echo "";
                exit;
            }
        }
    }
    
    protected function do_post_request($url, $data, $optional_headers = null)
    {
       $params = array('http' => array(
                    'method' => 'POST',
                    'content' => $data
                 ));
       if ($optional_headers !== null) {
          $params['http']['header'] = $optional_headers;
       }
       $ctx = stream_context_create($params);
       $fp = @fopen($url, 'rb', false, $ctx);
       if (!$fp) {
          throw new Exception("Problem with $url, $fp");
       }
       $response = @stream_get_contents($fp);
       if ($response === false) {
          throw new Exception("Problem reading data from $url, $php_errormsg");
       }
       return $response;
    }
}

?>
